export class ImageCompressor {
  /**
   * 压缩图片
   * @param {File} file - 图片文件对象
   * @param {Object} options - 压缩选项
   * @param {number} [options.maxWidth=1920] - 最大宽度
   * @param {number} [options.maxHeight=1080] - 最大高度
   * @param {number} [options.quality=0.8] - 压缩质量 (0-1)
   * @param {string} [options.outputType='image/jpeg'] - 输出类型
   * @returns {Promise<Blob>} - 返回压缩后的Blob对象
   */
  static async compress (file, options = {}) {
    const {
      maxWidth = 1920,
      maxHeight = 1080,
      quality = 0.8,
      outputType = "image/jpeg",
    } = options;

    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = function (event) {
        const img = new Image();
        img.onload = function () {
          const canvas = document.createElement("canvas");
          let width = img.width;
          let height = img.height;

          // 计算缩放比例
          if (width > maxWidth || height > maxHeight) {
            const ratio = Math.min(maxWidth / width, maxHeight / height);
            width = width * ratio;
            height = height * ratio;
          }

          // 设置canvas尺寸
          canvas.width = width;
          canvas.height = height;

          // 绘制图像
          const ctx = canvas.getContext("2d");
          ctx.drawImage(img, 0, 0, width, height);

          // 转换为Blob
          canvas.toBlob(
            (blob) => {
              if (!blob) {
                reject(new Error("Canvas to Blob conversion failed"));
                return;
              }
              resolve(blob);
            },
            outputType,
            quality,
          );
        };
        img.onerror = reject;
        img.src = event.target.result;
      };
      reader.onerror = reject;
      reader.readAsDataURL(file);
    });
  }

  /**
   * 压缩图片并返回File对象
   * @param {File} file - 图片文件对象
   * @param {Object} options - 压缩选项
   * @returns {Promise<File>} - 返回压缩后的File对象
   */
  static async compressToFile (file, options = {}) {
    const blob = await this.compress(file, options);
    return new File([blob], file.name, {
      type: blob.type,
      lastModified: Date.now(),
    });
  }
}
